<template>
  <Modal
    :get-container="false"
    :closable="false"
    :visible="visible"
    :destroyOnClose="true"
    @ok="onSubmit"
    @cancel="onClose"
  >
    <Divider orientation="left"
      ><span style="margin-right: 8px; font-weight: bolder">{{ title }}</span></Divider
    >
    <BasicForm @register="registerForm"></BasicForm>
  </Modal>
</template>

<script lang="ts" setup>
import { Modal, Divider } from 'ant-design-vue';
import { nextTick, ref } from 'vue';
import BasicForm from '/@/components/BasicForm/BasicForm.vue';
import { useBasicForm } from '/@/components/BasicForm/hooks/useBasicForm';
import { apiSchema } from '/@/views/system-mgmt/app-resource-mgmt/form';
import { ResourceParams } from '/@/api/system-mgmt/app-resource-mgmt/model/resourceModel';
import { createResource, updateResource } from '/@/api/system-mgmt/app-resource-mgmt/resource';

const visible = ref(false);
const title = ref('');
const appId = ref();
const emit = defineEmits(['success']);
const parentId = ref();
const [registerForm, { validate, setFieldsValue }] = useBasicForm({
  labelWidth: 100,
  showActionButtonGroup: false,
  schemas: apiSchema,
});

const openModal = (info: any, appTempId: string, parentTempId: string) => {
  visible.value = true;
  nextTick(() => {
    setFieldsValue({ status: 0 });
  });
  appId.value = appTempId;
  parentId.value = parentTempId;
  if (info !== undefined) {
    title.value = '编辑Api信息';
    nextTick(async () => {
      await setFieldsValue(info);
    });
  } else {
    title.value = '新增Api';
  }
};
const onClose = async () => {
  visible.value = false;
};

const onSubmit = async () => {
  let params: ResourceParams = await validate();
  params.parentId = parentId.value;
  params.appId = appId.value;
  params.type = 'API';
  if (title.value === '新增Api') {
    await createResource(params);
  } else {
    await updateResource(params);
  }
  await emit('success');
  onClose();
};
defineExpose({ openModal, onClose, visible });
</script>
